package cn.tedu.csmall.cart.webapi.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

// Mybatis拦截器测试类
@Slf4j
// Mybatis拦截器配置声明用的注解
// 可以拦截多个jdbc中的对象
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class,Integer.class}
)})
public class MybatisInterceptor implements Interceptor {
    // 执行拦截MyBatis指令的方法
    // invocation:调用,其中包含着运行的指令的信息(包含sql语句指令的)
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("进入拦截器,准备拦截sql语句");
        // 通过参数invocation,要运行的sql语句对象
        BoundSql boundSql=((StatementHandler)invocation.getTarget()).getBoundSql();
        // boundSql对象中获得sql语句
        String sql=boundSql.getSql();
        log.info("要运行的sql语句为:{}",sql);
        return invocation.proceed();
    }
}
